import copy
import glob
import os.path
import sys
import threading
import time
import traceback
from concurrent.futures import ThreadPoolExecutor

import matplotlib
import pandas as pd

from PyQt5.QtCore import Qt, QDateTime, QThread
from PyQt5.QtWidgets import QFileDialog
from matplotlib import pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.dates import AutoDateLocator, DateFormatter
from pandas import Timestamp

from StressAna.Lib.Model import LabelsInit, Globalvariables
from StressAna.Lib.DataAna.AnkeDataAna import AnkeAna
from StressAna.Lib.DataAna.MonDataAna import MonAna
from StressAna.Lib.DataAna.TDDataAna import TDAna
from StressAna.UI.UI_Main import *

from StressAna.UI.UI_DataSyncTip import *

# warnings.filterwarnings('ignore')
matplotlib.use("Qt5Agg")
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei"]  # 设置默认字体
plt.rcParams["axes.unicode_minus"] = False  # 坐标轴正确显示正负号

'''
数据补数（取前一个值）
'''


def ana(data):
    for i, value in enumerate(data):
        if i > 0 and data[i] == 0:
            data[i] = data[i - 1]


'''
画布初始化
'''


class Figure_Canvas(FigureCanvas):
    def __init__(self, parent=None, width=12, height=8, dpi=100):
        self.fig = plt.Figure(figsize=(width, height), dpi=dpi, tight_layout=True)
        FigureCanvas.__init__(self, self.fig)  # 初始化父类
        self.setParent(parent)
        self.axes = self.fig.add_subplot(111)

    def drawFig(self, data_list=None, data_list2=None, labels=None, title='对比分析'):
        if data_list is None:
            data_list = []
        if data_list2 is None:
            data_list2 = []
        if labels is None:
            labels = []

        data_legend = []
        for idata in data_list:
            line = self.axes.plot(idata[0], idata[1])
            data_legend.append(line[0])

        if data_list2:
            self.ax2 = self.axes.twinx()
            for idata in data_list2:
                line = self.ax2.plot(idata[0], idata[1], alpha=0.8, linestyle='--')
                data_legend.append(line[0])
            self.ax2.set_ylabel("摄氏度/℃")

        self.axes.set_title(title, pad=25)
        self.axes.set_xlabel("时间")
        self.axes.set_ylabel("Mpa")

        locator = AutoDateLocator()
        date_fmt = DateFormatter("%Y-%m-%d %H:%M:%S")
        self.axes.xaxis.set_major_locator(locator)
        self.axes.xaxis.set_major_formatter(date_fmt)
        self.axes.tick_params(direction='in', length=6, width=2, labelsize=8)
        self.axes.xaxis.set_tick_params(labelrotation=45)
        self.axes.legend(data_legend, labels, loc=9, bbox_to_anchor=(0.5, -0.25), shadow=True, fancybox=True, ncol=4)


'''
数据对比类
'''


class Stress_csv(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.AkData_file_root_path = None
        self.TdData_file_root_path = None
        self.MonData_file_root_path = None
        self.setupUi(self)
        self.init()

    def init(self):
        self.TdData_file_root_path = r'D:\LK\TMV煤矿项目\应力数据\obsdata'
        self.AkData_file_root_path = r'D:\LK\TMV煤矿项目\应力数据\AK'
        self.MonData_file_root_path = r'D:\LK\TMV煤矿项目\应力数据\monidata'

        self.sID_TD_list = []
        self.sID_AK_list = []
        self.DF_ALL = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])
        self.DF_FILTER = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])
        self.DF_MON_ALL = pd.DataFrame(columns=['sID', 'time', 'temp', 'power'])
        self.FILTER_CONS = []
        self.TD_DATA_LIST = []
        self.SK_DATA_LIST = []

        self.sync_tip_dialog = None

        LabelsInit.sIDAttrInit()
        for i, dfi in Globalvariables.LABELS_DICT.groupby('length'):
            self.cb_CD.addItem(i)
        for i, dfi in Globalvariables.LABELS_DICT.groupby('wallThick'):
            self.cb_BH.addItem(i)
        for i, dfi in Globalvariables.LABELS_DICT.groupby('holeDepth'):
            self.cb_KS.addItem(i)
        for i, dfi in Globalvariables.LABELS_DICT.groupby('initialPress'):
            self.cb_CSY.addItem(i)

        now_day = time.strftime("%Y-%m-%d", time.localtime())
        self.dateEdit.setDateTime(QDateTime.fromString(f'{now_day}', "yyyy-MM-dd"))
        self.dateEdit_2.setDateTime(QDateTime.fromString(f'{now_day}', "yyyy-MM-dd"))
        self.DTEdit_start.setDateTime(QDateTime.fromString(f'{now_day} 00:00:00', "yyyy-MM-dd HH:mm:ss"))
        self.DTEdit_end.setDateTime(QDateTime.fromString(f'{now_day} 00:00:00', "yyyy-MM-dd HH:mm:ss"))
        self.actionOutCSV.triggered.connect(self.out_csv_slot)  # type: ignore
        self.actionInCSV.triggered.connect(self.in_csv_slot)  # type: ignore

        if os.path.exists(os.path.join(Globalvariables.DATA_PATH, 'obsdata.csv.gz')):
            self.statusbar.showMessage('开始导入本地数据文件.')
            print('开始导入本地数据文件.')
            self.in_csv_slot()
        self._init_sid_list()

    def _init_sid_list(self):
        for sID in Globalvariables.STATION_dict:
            if sID not in self.sID_TD_list:
                self.sID_TD_list.append(sID)
                newitem = QtWidgets.QListWidgetItem(f"{sID}:{LabelsInit.get_sIDAttr(f'{sID}')}")
                newitem.setCheckState(0)
                self.listWidget.addItem(newitem)
        for key, sID in Globalvariables.STATION_ANKE.items():
            if sID not in self.sID_AK_list:
                self.sID_AK_list.append(sID)
                newitem = QtWidgets.QListWidgetItem(f"{sID}-1:8M")
                newitem.setCheckState(False)
                self.listWidget_2.addItem(newitem)
                newitem = QtWidgets.QListWidgetItem(f"{sID}-2:14M")
                newitem.setCheckState(False)
                self.listWidget_2.addItem(newitem)

    '''
    导入泰德数据
    '''

    def load_tddata_slot(self):
        Dir = QFileDialog.getExistingDirectory(self, '选择泰德数据目录', self.TdData_file_root_path)
        if not Dir:
            return
        self.TdData_file_root_path = Dir

        if not self.sync_tip_dialog:
            self.sync_tip_dialog = SyncTipDialog()
        self.sync_tip_dialog.show()  # 以非模态对话框模式弹出
        load_tddata_thread = threading.Thread(target=self.load_tddata)
        load_tddata_thread.setDaemon(True)
        load_tddata_thread.start()
        self.statusbar.showMessage('正在加载泰德数据，请稍等...')

    def load_single_td_data(self, file):
        try:
            tddata = TDAna(file)
        except:
            print(traceback.format_exc())
            return
        print(f"完成 {file}")
        self.TD_DATA_LIST.append(tddata.df)

    def load_single_sk_data(self, file):
        try:
            aData = AnkeAna(file)
            for sID, dfi in aData.df.groupby('sID'):
                self.SK_DATA_LIST.append(dfi)
        except:
            print(traceback.format_exc())
            return
        print(f"完成 {file}")

    def load_tddata(self):
        dirs = glob.glob(f'{self.TdData_file_root_path}/**/*.txt', recursive=True)

        # with ThreadPoolExecutor(max_workers=1000) as threadPool:
        #     for file in dirs:
        #         threadPool.submit(self.load_single_td_data, file)
        for file in dirs:
            self.load_single_td_data(file)
        self.DF_ALL = pd.concat(self.TD_DATA_LIST)
        self.DF_ALL.reset_index(drop=True, inplace=True)

        if self.sync_tip_dialog:
            self.sync_tip_dialog.hide()
        self.statusbar.showMessage('加载泰德数据结束')

    '''
    导入思科赛德数据
    '''

    def load_skdata_slot(self):
        Dir = QFileDialog.getExistingDirectory(self, '选择安科数据目录', self.AkData_file_root_path)
        if not Dir:
            return
        self.AkData_file_root_path = Dir
        if not self.sync_tip_dialog:
            self.sync_tip_dialog = SyncTipDialog()
        self.sync_tip_dialog.show()  # 以非模态对话框模式弹出

        load_skdata_thread = threading.Thread(target=self.load_skdata)
        load_skdata_thread.setDaemon(True)
        load_skdata_thread.start()
        self.statusbar.showMessage('正在加载思科赛德数据，请稍等...')

    def load_skdata(self):
        # sk_id_list = list(Globalvariables.STATION_ANKE.values())
        # index_list = self.DF_ALL[(self.DF_ALL['sID'].isin(sk_id_list))].index
        # self.DF_ALL.drop(index_list, axis=0, inplace=True)
        dirs = glob.glob(f'{self.AkData_file_root_path}/**/*.xlsx', recursive=True)
        for file in dirs:
            self.load_single_sk_data(file)
        for df in self.SK_DATA_LIST:
            self.DF_ALL = pd.concat([self.DF_ALL, df])
        self.DF_ALL.reset_index(drop=True, inplace=True)

        if self.sync_tip_dialog:
            self.sync_tip_dialog.hide()
        self.statusbar.showMessage('加载思科赛德数据结束')

    '''
    导入泰德状态数据
    '''

    def load_mondata_slot(self):
        Dir = QFileDialog.getExistingDirectory(self, '选择泰德状态数据目录', self.MonData_file_root_path)
        if not Dir:
            return
        self.MonData_file_root_path = Dir

        if not self.sync_tip_dialog:
            self.sync_tip_dialog = SyncTipDialog()
        self.sync_tip_dialog.show()  # 以非模态对话框模式弹出
        load_mondata_thread = threading.Thread(target=self.load_mondata)
        load_mondata_thread.setDaemon(True)
        load_mondata_thread.start()
        self.statusbar.showMessage('正在加载泰德状态数据，请稍等...')

    def load_mondata(self):
        dirs = glob.glob(f'{self.MonData_file_root_path}/**/*.txt', recursive=True)

        self.MON_TD_LIST = []
        for file in dirs:
            mondata = MonAna(file)
            self.MON_TD_LIST.append(mondata.df)
        self.DF_MON_ALL = pd.concat(self.MON_TD_LIST)
        self.DF_MON_ALL.reset_index(drop=True, inplace=True)
        self.DF_ALL['time'] = self.DF_ALL['time'].astype('datetime64[ns]')
        self.DF_ALL = self.DF_ALL.merge(self.DF_MON_ALL, on=['sID', 'time'], how='left')
        if self.sync_tip_dialog:
            self.sync_tip_dialog.hide()
        self.statusbar.showMessage('加载泰德状态数据结束')

    '''
    绘制波形
    '''

    def draw_slot(self):
        start_time_str = self.dateEdit.dateTime().date().toString("yyyy-MM-dd 00:00:00")
        end_time_str = self.dateEdit_2.dateTime().date().toString("yyyy-MM-dd 23:59:59")

        if start_time_str >= end_time_str:
            print('开始时间不能大于结束时间！')
            return

        sIDs = []
        labels = []
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).checkState():
                sIDs.append(self.listWidget.item(i).text())
        for i in range(self.listWidget_2.count()):
            if self.listWidget_2.item(i).checkState():
                sIDs.append(f"{self.listWidget_2.item(i).text()}:(思科赛德数据)")

        data_list = []
        data_list2 = []
        curDataList = []  # 开始压力和结束压力
        start_data = 0  # 找到开始的压力 默认0
        end_data = 0  # 找到结束的压力 默认0
        self.DF_FILTER = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])

        ids = [x.split(':')[0].split('-')[0] for x in sIDs]
        ids = list(set(ids))
        for sID in ids:
            _df = self.DF_ALL[
                (start_time_str <= self.DF_ALL['time']) & (self.DF_ALL['time'] <= end_time_str) & (
                        self.DF_ALL['sID'] == sID)]
            self.DF_FILTER = self.DF_FILTER._append(_df)

        for item in sIDs:
            iName = item.split(':')[0]
            sID, chnNum = iName.split('-')
            _df = self.DF_ALL[
                (start_time_str <= self.DF_ALL['time']) & (self.DF_ALL['time'] <= end_time_str) & (
                        self.DF_ALL['sID'] == sID)]
            _df.loc[:, 'time'] = _df.loc[:, 'time'].astype('datetime64[ns]')
            x = []
            y = []
            for time, dfi in _df.groupby('time'):
                x.append(time)
                y.append(dfi.iloc[0][f'ch{chnNum}'])
            if self.cb_comple.checkState():
                ana(y)

            for i in y:
                if str(i) != 'nan':
                    start_data = i
                    break
            for i in y[::-1]:
                if str(i) != 'nan':
                    end_data = i
                    break

            # 不显示-9999的数据
            CtrX = []
            CtrY = []
            for i, value in enumerate(y):
                if value != -9999:
                    CtrX.append(x[i])
                    CtrY.append(value)
            data_list.append((CtrX, CtrY))
            curDataList.append((iName, start_data, end_data))
        if not data_list:
            print('没有找到数据！')
            return

        if self.cb_temp.checkState():
            names_list = []
            for item in sIDs:
                iName = item.split(':')[0]
                sID, chnNum = iName.split('-')
                if sID in names_list:
                    continue
                names_list.append(sID)
                df_sel = self.DF_ALL[
                    (start_time_str <= self.DF_ALL['time']) & (self.DF_ALL['time'] <= end_time_str) & (
                            self.DF_ALL['sID'] == sID) & (
                        self.DF_ALL['temp'])]
                if df_sel.empty:
                    continue
                df_sel.reset_index(drop=True, inplace=True)
                df_sel.loc[:, 'time'] = df_sel.loc[:, 'time'].astype('datetime64[ns]')
                x = df_sel['time'].to_list()
                y = df_sel['temp'].to_list()
                data_list2.append((x, y))
                labels.append(f'{sID}-温度')
            sIDs.extend(labels)

        # 显示当前波形开始压力值和结束压力值
        # self.textBrowser.setText('\n'.join(curDataList))
        self.textBrowser_2.clear()
        self.textBrowser_3.clear()
        self.textBrowser_4.clear()
        text_sids = []
        text_values1 = []
        text_values2 = []
        for row, row_values in enumerate(curDataList):
            text_sids.append(f'{row_values[0]}')
            text_values1.append(f'{row_values[1]}')
            text_values2.append(f'{row_values[2]}')
        self.textBrowser_2.setText('\n'.join(text_sids))
        self.textBrowser_3.setText('\n'.join(text_values1))
        self.textBrowser_4.setText('\n'.join(text_values2))

        self.setViewTail(data_list=data_list, data_list2=data_list2, labels=sIDs)

        self.cB_sidFilter.clear()
        for sid in sIDs:
            self.cB_sidFilter.addItem(sid)
        self.FILTER_CONS = []
        self.pb_draw_max.show()

    def fliter_draw_slot(self):
        if self.DF_FILTER.empty:
            self.statusbar.showMessage('请先绘制波形')
            return
        start_time_str = self.dateEdit.dateTime().date().toString("yyyy-MM-dd 00:00:00")
        end_time_str = self.dateEdit_2.dateTime().date().toString("yyyy-MM-dd 23:59:59")

        if start_time_str >= end_time_str:
            print('开始时间不能大于结束时间！')
            return

        filter_start_time_str = self.DTEdit_start.dateTime().toPyDateTime()
        filter_end_time_str = self.DTEdit_end.dateTime().toPyDateTime()
        filter_sid_str = self.cB_sidFilter.currentText()
        filter_sid, filter_chnNum = filter_sid_str.split(':')[0].split('-')
        self.FILTER_CONS.append((filter_start_time_str, filter_end_time_str, filter_sid, filter_chnNum))
        if filter_start_time_str >= filter_end_time_str:
            print('开始时间不能大于结束时间！')
            return

        sIDs = []
        labels = []
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).checkState():
                sIDs.append(self.listWidget.item(i).text())
        for i in range(self.listWidget_2.count()):
            if self.listWidget_2.item(i).checkState():
                sIDs.append(f"{self.listWidget_2.item(i).text()}:(思科赛德数据)")

        data_list = []
        data_list2 = []
        curDataList = []  # 开始压力和结束压力
        start_data = 0  # 找到开始的压力 默认0
        end_data = 0  # 找到结束的压力 默认0

        for item in sIDs:
            iName = item.split(':')[0]
            sID, chnNum = iName.split('-')
            # if sID == filter_sid:
            #     self.DF_FILTER = self.DF_FILTER[
            #         ((self.DF_FILTER['time'] <= filter_start_time_str) | (filter_end_time_str <= self.DF_FILTER['time'])) & (
            #                 self.DF_FILTER['sID'] == filter_sid)]

            self.DF_FILTER.loc[:, 'time'] = self.DF_FILTER.loc[:, 'time'].astype('datetime64[ns]')
            _df = self.DF_FILTER[(self.DF_FILTER['sID'] == sID)]
            x = _df['time'].to_list()
            y = _df[f'ch{chnNum}'].to_list()
            if self.cb_comple.checkState():
                ana(y)

            # 不显示-9999的数据
            CtrX = []
            CtrY = []
            for i in range(len(x)):
                skip_flag = False
                if y[i] == -9999:
                    continue
                for cons in self.FILTER_CONS:
                    filter_start_time, filter_end_time, f_sid, f_chnNum = cons
                    if f_sid == sID and f_chnNum == chnNum and (filter_start_time <= x[i] <= filter_end_time):
                        skip_flag = True
                        break
                if skip_flag:
                    continue
                CtrX.append(x[i])
                CtrY.append(y[i])
            data_list.append((CtrX, CtrY))

            for i in CtrY:
                if str(i) != 'nan':
                    start_data = i
                    break
            for i in CtrY[::-1]:
                if str(i) != 'nan':
                    end_data = i
                    break
            curDataList.append((iName, start_data, end_data))
        if not data_list:
            print('没有找到数据！')
            return

        if self.cb_temp.checkState():
            names_list = []
            for item in sIDs:
                iName = item.split(':')[0]
                sID, chnNum = iName.split('-')
                if sID in names_list:
                    continue
                names_list.append(sID)
                df_sel = self.DF_ALL[
                    (start_time_str <= self.DF_ALL['time']) & (self.DF_ALL['time'] <= end_time_str) & (
                            self.DF_ALL['sID'] == sID) & (
                        self.DF_ALL['temp'])]
                if df_sel.empty:
                    continue
                df_sel.reset_index(drop=True, inplace=True)
                x = df_sel['time'].to_list()
                y = df_sel['temp'].to_list()
                data_list2.append((x, y))
                labels.append(f'{sID}-温度')
            sIDs.extend(labels)

        # 显示当前波形开始压力值和结束压力值
        # self.textBrowser.setText('\n'.join(curDataList))
        self.textBrowser_2.clear()
        self.textBrowser_3.clear()
        self.textBrowser_4.clear()
        text_sids = []
        text_values1 = []
        text_values2 = []
        for row, row_values in enumerate(curDataList):
            text_sids.append(f'{row_values[0]}')
            text_values1.append(f'{row_values[1]}')
            text_values2.append(f'{row_values[2]}')
        self.textBrowser_2.setText('\n'.join(text_sids))
        self.textBrowser_3.setText('\n'.join(text_values1))
        self.textBrowser_4.setText('\n'.join(text_values2))

        self.setViewTail(data_list=data_list, data_list2=data_list2, labels=sIDs)

    '''
    绘制最大值波形
    '''

    def draw_max_slot(self):
        self.drawPic.setEnabled(False)
        start_time_str = self.dateEdit.dateTime().date().toString("yyyy-MM-dd 00:00:00")
        end_time_str = self.dateEdit_2.dateTime().date().toString("yyyy-MM-dd 23:59:59")

        sIDs = []
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).checkState():
                sIDs.append(self.listWidget.item(i).text())
        for i in range(self.listWidget_2.count()):
            if self.listWidget_2.item(i).checkState():
                sIDs.append(self.listWidget_2.item(i).text())

        data_list = []
        if 'date' not in self.DF_ALL.columns:
            self.DF_ALL['date'] = self.DF_ALL['time'].astype('str').apply(lambda x: x[:10])
        for item in sIDs:
            iName = item.split(':')[0]
            sID, chnNum = iName.split('-')
            df_sel = self.DF_ALL[
                (start_time_str <= self.DF_ALL['time']) & (self.DF_ALL['time'] <= end_time_str) & (
                        self.DF_ALL['sID'] == sID)]
            x = []
            y = []
            for idate, dfi in df_sel.groupby('date'):
                x.append(Timestamp(f"{idate} 00:00:00"))
                y.append(dfi[f'ch{chnNum}'].max())

            # 不显示-9999的数据
            CtrX = []
            CtrY = []
            for i, value in enumerate(y):
                if value != -9999:
                    CtrX.append(x[i])
                    CtrY.append(value)
            data_list.append((CtrX, CtrY))
            # data_list.append((x, y))
        self.setViewTail(data_list=data_list, labels=sIDs)

    '''
    展示波形
    '''

    def setViewTail(self, data_list=None, data_list2=None, labels=None):
        # 图例
        labels = LabelsInit.labelsInit(labels)
        self.drawPic.setEnabled(False)

        self.fig_canvas = Figure_Canvas()  # 实例化类
        self.fig_canvas.drawFig(data_list=data_list, data_list2=data_list2, labels=labels,
                                title=self.lineEdit.text())  # 调用类方法，作图
        self.graphicscene = QtWidgets.QGraphicsScene()  # 创建一个QGraphicsScene，因为加载的图形（FigureCanvas）不能直接放到graphicview控件中，必须先放到graphicScene，然后再把graphicscene放到graphicview中
        self.graphicscene.addWidget(self.fig_canvas)  # 把图形放到QGraphicsScene中，注意：图形是作为一个QWidget放到QGraphicsScene中的
        self.graphicsView.setScene(self.graphicscene)  # 把QGraphicsScene放入QGraphicsView
        self.graphicsView.show()  # 调用show方法呈现图形

        self.drawPic.setEnabled(True)

    def draw_finish_slot(self):
        self.drawPic.setEnabled(True)

    '''
    泰德数据全选
    '''

    def selall_slot1(self):
        for i in range(self.listWidget.count()):
            if not self.listWidget.item(i).checkState():
                self.listWidget.item(i).setCheckState(2)

    '''
    思科数据全选
    '''

    def selall_slot2(self):
        for i in range(self.listWidget_2.count()):
            if not self.listWidget_2.item(i).checkState():
                self.listWidget_2.item(i).setCheckState(2)

    '''
    泰德数据取消全选
    '''

    def selnoall_slot1(self):
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).checkState():
                self.listWidget.item(i).setCheckState(0)

    '''
    思科数据取消全选
    '''

    def selnoall_slot2(self):
        for i in range(self.listWidget_2.count()):
            if self.listWidget_2.item(i).checkState():
                self.listWidget_2.item(i).setCheckState(0)

    def sel_addr_slot(self):
        CD = self.cb_CD.currentText()
        BH = self.cb_BH.currentText()
        KS = self.cb_KS.currentText()
        CSY = self.cb_CSY.currentText()
        df = copy.deepcopy(Globalvariables.LABELS_DICT)
        if CD != '全部':
            df = df[(df['length'] == CD)]
        if BH != '全部':
            df = df[(df['wallThick'] == BH)]
        if KS != '全部':
            df = df[(df['holeDepth'] == KS)]
        if CSY != '全部':
            df = df[(df['initialPress'] == CSY)]
        # df_sel = df[(df['length']==CD) & (df['wallThick']==BH) & (df['holeDepth']==KS) & (df['initialPress']==CSY)]
        sta_list = df['sta'].unique().tolist()
        self.selnoall_slot1()
        for sta in sta_list:
            for i in range(self.listWidget.count()):
                if sta in self.listWidget.item(i).text():
                    self.listWidget.item(i).setCheckState(2)

    def re_sel_slot(self):
        pass

    def out_csv_slot(self):
        self.statusbar.showMessage('开始导出数据')
        self.DF_ALL.to_csv(os.path.join(Globalvariables.DATA_PATH, 'obsdata.csv.gz'), compression='gzip', index=False)
        self.statusbar.showMessage('导出数据文件完成！')
        print('导出数据文件完成！')

    def in_csv_slot(self):
        self.DF_ALL = pd.read_csv(os.path.join(Globalvariables.DATA_PATH, 'obsdata.csv.gz'), compression='gzip',
                                  low_memory=False)
        print('导入数据文件完成！')
        self.statusbar.showMessage('导入数据文件完成！')

    def temp_save_slot(self):
        # for cons in self.FILTER_CONS:
        #     filter_start_time, filter_end_time, f_sid, f_chnNum = cons
        #     if f_sid == sID and f_chnNum == chnNum and (filter_start_time <= x[i] <= filter_end_time):
        #     self.DF_FILTER = self.DF_FILTER[
        #         ((self.DF_FILTER['time'] <= filter_start_time_str) | (filter_end_time_str <= self.DF_FILTER['time'])) & (
        #                 self.DF_FILTER['sID'] == filter_sid)]
        pass

    def restore_slot(self):
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'Y03') & (self.DF_ALL['time'] >= '2024-03-01'), 'ch1'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'Y03') & (self.DF_ALL['time'] >= '2024-03-01'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'Y04') & (self.DF_ALL['time'] >= '2024-03-09'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'Y05') & (self.DF_ALL['time'] >= '2024-03-19'), 'ch1'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'Y05') & (self.DF_ALL['time'] >= '2024-03-19'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'Y06') & (self.DF_ALL['time'] >= '2024-03-20'), 'ch1'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'Y06') & (self.DF_ALL['time'] >= '2024-03-20'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'Y07'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'Y09') & (self.DF_ALL['time'] >= '2024-01-24') & (
                    self.DF_ALL['time'] <= '2024-01-25'), 'ch2'] = -9999

        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G01') & (self.DF_ALL['time'] >= '2024-03-01'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G02') & (self.DF_ALL['time'] >= '2024-03-01'), 'ch1'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G01') & (self.DF_ALL['time'] >= '2024-03-04'), 'ch1'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G02') & (self.DF_ALL['time'] >= '2024-03-11'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G04') & (self.DF_ALL['time'] >= '2024-03-20'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G06') & (self.DF_ALL['time'] <= '2024-01-25'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G07') & (self.DF_ALL['time'] <= '2024-01-25'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G08') & (self.DF_ALL['time'] >= '2024-03-10'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G09') & (self.DF_ALL['time'] <= '2024-01-25'), 'ch1'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G11') & (self.DF_ALL['time'] <= '2024-01-25'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G12') & (self.DF_ALL['time'] <= '2024-01-25'), 'ch1'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'G12') & (self.DF_ALL['time'] <= '2024-01-25'), 'ch2'] = -9999

        self.DF_ALL.loc[(self.DF_ALL['sID'].str.contains('J')) & (self.DF_ALL['time'] < '2024-02-01'), 'ch1'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'].str.contains('J')) & (self.DF_ALL['time'] < '2024-02-01'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'J04'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'J05'), 'ch1'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'J03') & (self.DF_ALL['time'] >= '2024-02-05') & (
                    self.DF_ALL['time'] <= '2024-02-06'), 'ch1'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'J03') & (self.DF_ALL['time'] >= '2024-02-05') & (
                    self.DF_ALL['time'] <= '2024-02-06'), 'ch2'] = -9999
        self.DF_ALL.loc[(self.DF_ALL['sID'] == 'J05') & (self.DF_ALL['time'] < '2024-02-06'), 'ch2'] = -9999

        self.draw_slot()
'''
数据同步提示框
'''


class SyncTipDialog(QtWidgets.QDialog, Ui_DataSyncTip):
    def __init__(self):
        super(SyncTipDialog, self).__init__()
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)


class LoadDataQThread(QThread):
    def __init__(self):
        super().__init__()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    Main = Stress_csv()
    Main.show()
    sys.exit(app.exec())
